package com.itheima.filter;

import com.itheima.utilis.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取请求路径
        String requestURL = request.getRequestURL().toString();

        //2、判断是否是登录请求
        //如果是登录请求，直接放行
        if (requestURL.contains("/login")) {
            log.info("登录请求，直接放行！");
            filterChain.doFilter(request, response);
            return;//注意return不能省略
        }

        //3、获取请求头中的令牌
        String jwt = request.getHeader("token");
        if (jwt == null) {
            log.info("请求头中没有token");
            //没有携带令牌，拦截请求，封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            return;
        }

        //4、解析令牌，判断令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            //令牌不正确，拦截请求，封装错误结果
            log.info("令牌不正确，拦截请求！");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            return;
        }

        //5、令牌正确，放行
        log.info("令牌正确，放行！");
        filterChain.doFilter(request, response);
    }
}
